#!/bin/sh
PACKAGE_BASE="/var/packages/nastool/target"
PYTHON_BIN="/var/packages/python38/target/bin/python3"
PACKAGE_SSS="/var/packages/${PACKAGE_NAME}/scripts/start-stop-status"

preinst ()
{
    exit 0
}

install_service(){
  chmod +x "/var/packages/nastool/scripts/"
  # 安装pip
  # "${PYTHON_BIN}" "${PACKAGE_BASE}/get-pip.py"
  # pip安装依赖包
  "${PYTHON_BIN}" -m pip install --no-index --find-links="${PACKAGE_BASE}/wheelhouse" -r "${PACKAGE_BASE}/requirements.txt"
  # 检测Pthon版本
  PYV=$(${PYTHON_BIN} -V 2>&1 | sed 's/.* \([0-9]\).\([0-9]\).*/\1.\2/')
  PYTHON_PACKAGE="/var/packages/python38/target/lib/python3.8/site-packages"
  echo "${PACKAGE_BASE}/" > "${PYTHON_PACKAGE}/nas-tools.pth"
}

postinst ()
{
    install_service
    exit 0
}

preuninst ()
{
    exit 0
}

postuninst ()
{
    exit 0
}

preupgrade() {
    # 停用套件
    "${PACKAGE_SSS}" stop

    # 备份数据文件...
    if [ -d "/tmp" ]; then
        DIRS4BACKUP="config"
        for DIR in $DIRS4BACKUP; do
            if [ -d "${PACKAGE_BASE}/${DIR}" ]; then
                mkdir -p "/tmp/${PACKAGE_NAME}_upgrade/${DIR}"
                cp -rf "${PACKAGE_BASE}/${DIR}"/* "/tmp/${PACKAGE_NAME}_upgrade/${DIR}/"
                rm -rf "${PACKAGE_BASE}/${DIR}"
            elif [ -f "${PACKAGE_BASE}/${DIR}" ]; then
                cp -rf "${PACKAGE_BASE}/${DIR}" "/tmp/${PACKAGE_NAME}_upgrade/"
            fi
        done
    fi

    exit 0
}

postupgrade() {
    # 恢复数据文件...
    if [ -d "/tmp/${PACKAGE_NAME}_upgrade" ]; then
        for DIR in `ls "/tmp/${PACKAGE_NAME}_upgrade"`
        do
            if [ -d "/tmp/${PACKAGE_NAME}_upgrade/${DIR}" ]; then
                [ ! -d "${PACKAGE_BASE}/${DIR}" ] && mkdir "${PACKAGE_BASE}/${DIR}"
                cp -rf "/tmp/${PACKAGE_NAME}_upgrade/${DIR}"/* "${PACKAGE_BASE}/${DIR}/"
                rm -rf "/tmp/${PACKAGE_NAME}_upgrade/${DIR}"
            elif [ -f "/tmp/${PACKAGE_NAME}_upgrade/${DIR}" ]; then
                cp -rf "/tmp/${PACKAGE_NAME}_upgrade/${DIR}" "${PACKAGE_BASE}/"
            fi
        done
        rm -rf "/tmp/${PACKAGE_NAME}_upgrade"
    fi
    exit 0
}
